﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "GbmpGraphicsNodeUtils.h"
#include "GraphicsNodeUtils.h"
#include "IGraphicsElementShape.h"
#include "IGraphicsNodeGroup.h"
#include "IGraphicsBRepBody.h"
#include "IGraphicsNodePathCollector.h"
#include "IDocument.h"
#include "ICurve3d.h"
#include "ICurve3dCurve3dIntersection.h"
#include "Intervald.h"
#include "AlgorithmIntersect.h"
#include "AlgorithmPositionJudge.h"
#include "BodiesPositionTypes.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"


using namespace gcmp;

gcmp::OwnerPtr<gcmp::IGraphicsNodeGroup> GbmpGraphicsNodeUtils::TransferGRepToGGroup(OwnerPtr<IGraphicsElementShape> pGRep)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pGRep, L"invalid parameter",L"GDMPLab",L"2024-03-30");
    OwnerPtr<IGraphicsNodeGroup> oGGroup = IGraphicsNodeGroup::Create();

    oGGroup->GetChildrenFw().swap(pGRep->GetChildrenFw());
    oGGroup->SetGraphicsStyleId(pGRep->GetGraphicsStyleId());
    oGGroup->SetGraphicsMaterialId(pGRep->GetGraphicsMaterialId());
    oGGroup->SetFlags(pGRep->GetFlags());
    oGGroup->SetVisibility(pGRep->GetVisibility());
    return oGGroup;
}

OwnerPtr<IGraphicsBRepBody> GbmpGraphicsNodeUtils::GetGRepBody(const IDocument* pDoc, const IGraphicsElementShape* pGRep)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"pDoc无效指针",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pGRep, L"pGRep无效指针",L"GDMPLab",L"2024-03-30");
    std::vector<const IGraphicsBRepBody*> gbodies;
    std::vector<Matrix4d> transforms;
    std::vector<std::vector<const IGraphicsNode*>> paths;
    GraphicsNodeUtils::CollectBRepBodies(pDoc, pGRep, &gbodies, &transforms, &paths);

    //找出实体Body，默认墙只有一个实体，排除Shell Body，比如墙的中心面，族中作为项目参照的参照平面等
    int solidBodyIndex = -1;
    FOR_EACH_INDEX(gbodyIndex, gbodies)
    {
        if (!gbodies[gbodyIndex]->IsShell())
        {
            solidBodyIndex = gbodyIndex;
            break;
        }
    }

    if (solidBodyIndex == -1)
        return nullptr;

    OwnerPtr<IGraphicsBRepBody> opGBody = TransferOwnershipCast<IGraphicsBRepBody>(gbodies[solidBodyIndex]->Clone());
    bool transformCode = opGBody->Transform(transforms[solidBodyIndex]);
    if (!transformCode)
    {
        return nullptr;
    }

    return opGBody;
}

std::vector<OwnerPtr<IGraphicsBRepBody>> GbmpGraphicsNodeUtils::GetAllGrepBodys(const IDocument* pDoc, const IGraphicsElementShape* pGRep)
{
    std::vector<OwnerPtr<IGraphicsBRepBody>> result;
    DBG_WARN_AND_RETURN_UNLESS(pDoc && pGRep, result, L"param inputed is invalid!",L"GDMPLab",L"2024-03-30");
    std::vector<const IGraphicsBRepBody*> gbodies;
    std::vector<Matrix4d> transforms;
    std::vector<std::vector<const IGraphicsNode*>> paths;
    GraphicsNodeUtils::CollectBRepBodies(pDoc, pGRep, &gbodies, &transforms, &paths);

    for (size_t index = 0; index < gbodies.size(); ++index)
    {
        const IGraphicsBRepBody* pCurrentBody = gbodies[index];
        if (pCurrentBody && !pCurrentBody->IsShell())
        {
            OwnerPtr<IGraphicsBRepBody> opGBody = TransferOwnershipCast<IGraphicsBRepBody>(pCurrentBody->Clone());
            DBG_WARN_AND_CONTINUE_UNLESS(opGBody, L"克隆Body失败",L"GDMPLab",L"2024-03-30");
            bool flag = opGBody->Transform(transforms[index]);

            if (!flag)
                return result;

            result.emplace_back(TransferOwnership(opGBody));
        }
    }

    return result;
}

Box3d GbmpGraphicsNodeUtils::ExpandBox3dExceptZValue(Box3d &box, double size)
{
    DBG_WARN_AND_RETURN_UNLESS(size > -1 * Constants::DOUBLE_EPS, Box3d(), L"传入size值不能小于0",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_UNLESS(!box.IsEmpty(), Box3d(), L"包围盒为空",L"GDMPLab",L"2024-03-30");
    Vector3d ptMin = box.GetMinPoint();
    Vector3d ptMax = box.GetMaxPoint();
    ptMin.SetX(ptMin.GetX() - size);
    ptMin.SetY(ptMin.GetY() - size);

    ptMax.SetX(ptMax.GetX() + size);
    ptMax.SetY(ptMax.GetY() + size);

    return Box3d(ptMin, ptMax);
}

bool GbmpGraphicsNodeUtils::IntersectCurve3dsByExtend(const ICurve3d *pFirGmICurve3d, const ICurve3d *pSecGmICurve3d, std::vector<Vector3d> &intersectPoints)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pFirGmICurve3d, L"无效pFirGmICurve3d",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pSecGmICurve3d, L"无效pSecGmICurve3d",L"GDMPLab",L"2024-03-30");
    std::vector<OwnerPtr<ICurve3dCurve3dIntersection>> pIntersects;
    intersectPoints.clear();

    OwnerPtr<gcmp::ICurve3d> opFirCurve = TransferOwnershipCast<gcmp::ICurve3d>(pFirGmICurve3d->Clone());
    OwnerPtr<gcmp::ICurve3d> opSecCurve = TransferOwnershipCast<gcmp::ICurve3d>(pSecGmICurve3d->Clone());
    opFirCurve->SetLimits(Intervald(opFirCurve->GetStartLimit() - Constants::MAX_MODEL_SIZE, opFirCurve->GetEndLimit() + Constants::MAX_MODEL_SIZE));
    opSecCurve->SetLimits(Intervald(opSecCurve->GetStartLimit() - Constants::MAX_MODEL_SIZE, opSecCurve->GetEndLimit() + Constants::MAX_MODEL_SIZE));
    if (AlgorithmIntersect::Intersect(opFirCurve.get(), opSecCurve.get(), pIntersects, Constants::DISTANCE_ITERATION_EPS))
    {
        FOR_EACH(pInter, pIntersects)
        {
            if (pInter->GetIntersectType() == CurveCurveIntersectTypes::CurveCurveNormalType)
            {
                intersectPoints.push_back(pInter->GetIntersectPoint());
            }
        }
    }

    return !intersectPoints.empty();
}

bool gcmp::GbmpGraphicsNodeUtils::IsIntersect(const IDocument* pDoc, const IGraphicsElementShape*pFirstGRep, const IGraphicsElementShape *pSecondGRep)
{
    BodiesPositionTypes posType = Intersect(pDoc, pFirstGRep, pSecondGRep, true);
    if (posType == BodiesPositionTypes::Intersect)
    {
        return true;
    }

    return false;
}

BodiesPositionTypes gcmp::GbmpGraphicsNodeUtils::Intersect(const IDocument* pDoc, const IGraphicsElementShape*pFirstGRep, const IGraphicsElementShape *pSecondGRep, bool useBox)
{
    DBG_WARN_AND_RETURN_UNLESS(pDoc, BodiesPositionTypes::Separation, L"pDoc无效指针",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_UNLESS(pFirstGRep, BodiesPositionTypes::Separation, L"pFirstGRep无效指针",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_UNLESS(pSecondGRep, BodiesPositionTypes::Separation, L"pSecondGRep无效指针",L"GDMPLab",L"2024-03-30");
    BodiesPositionTypes res = BodiesPositionTypes::Unknown;
    if (useBox)
    {
        gcmp::Box3d firstBox = pFirstGRep->GetBox();
        gcmp::Box3d secondBox = pSecondGRep->GetBox();
        if (!firstBox.IsIntersect(secondBox))
        {
            return BodiesPositionTypes::Separation;
        }
    }

    std::vector<OwnerPtr<IGraphicsBRepBody>> firstGRepBodies = GraphicsNodeUtils::GetGraphicsBRepBodies(pDoc, pFirstGRep);
    std::vector<OwnerPtr<IGraphicsBRepBody>> secondGRepBodies = GetGRepBodies(pDoc, pSecondGRep);
    if (firstGRepBodies.size() == 0 || secondGRepBodies.size() == 0)
        return BodiesPositionTypes::Unknown;

    std::vector<BodiesPositionTypes> bodysPositionTypes;
    FOR_EACH(firstGRepBody, firstGRepBodies)
    {
        FOR_EACH(secondGRepBody, secondGRepBodies)
        {
            if (Intersect(firstGRepBody.get(), secondGRepBody.get()) == BodiesPositionTypes::Intersect) // 有一个相交直接返回
                return BodiesPositionTypes::Intersect;
            else if (!firstGRepBody || !secondGRepBody)
                bodysPositionTypes.push_back(BodiesPositionTypes::Unknown);
            else
                bodysPositionTypes.push_back(Intersect(firstGRepBody.get(), secondGRepBody.get()));
        }
    }

    std::sort(bodysPositionTypes.begin(), bodysPositionTypes.end());
    if (*bodysPositionTypes.cbegin() == BodiesPositionTypes::Unknown)
        res = BodiesPositionTypes::Unknown;
    else if (*bodysPositionTypes.cbegin() == BodiesPositionTypes::Tangent)
        res = BodiesPositionTypes::Tangent;
    else
        res = BodiesPositionTypes::Separation;

    return res;
}

BodiesPositionTypes gcmp::GbmpGraphicsNodeUtils::Intersect(const IGraphicsBRepBody* pFirstBody, const IGraphicsBRepBody *pSecondBody)
{
    DBG_WARN_AND_RETURN_UNLESS(pFirstBody, BodiesPositionTypes::Unknown, L"pFirstBody无效指针",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_UNLESS(pSecondBody, BodiesPositionTypes::Unknown, L"pSecondBody无效指针",L"GDMPLab",L"2024-03-30");

    const IBody* pFirstGmIBody = pFirstBody->GetGeometry();
    const IBody* pSecondGmIBody = pSecondBody->GetGeometry();

    DBG_WARN_AND_RETURN_UNLESS(pFirstGmIBody, BodiesPositionTypes::Separation, L"pFirstGmIBody无效指针",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_UNLESS(pSecondGmIBody, BodiesPositionTypes::Separation, L"pSecondGmIBody无效指针",L"GDMPLab",L"2024-03-30");

    return AlgorithmPositionJudge::GetPosition(pFirstGmIBody, pSecondGmIBody);
}

std::vector<OwnerPtr<IGraphicsBRepBody>> gcmp::GbmpGraphicsNodeUtils::GetGRepBodies(const IDocument * pDoc, const IGraphicsElementShape * pGRep)
{
    std::vector<OwnerPtr<IGraphicsBRepBody>> res;
    std::vector<const IGraphicsBRepBody*> gbodies;
    std::vector<Matrix4d> transforms;
    std::vector<std::vector<const IGraphicsNode*>> paths;
    GraphicsNodeUtils::CollectBRepBodies(pDoc, pGRep, &gbodies, &transforms, &paths);

    FOR_EACH_INDEX(index, gbodies)
    {
        OwnerPtr<IGraphicsBRepBody> opGBody = TransferOwnershipCast<IGraphicsBRepBody>(gbodies[index]->Clone());
        bool transformCode = opGBody->Transform(transforms[index]);
        if (transformCode)
        {
            res.push_back(TransferOwnership(opGBody));
        }
    }

    return res;
}

bool gcmp::GbmpGraphicsNodeUtils::IsPointInsideOrOnBody(const IDocument* pDoc, const Vector3d& pos, const IGraphicsElementShape*pGRep)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pDoc, L"pDoc无效指针",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pGRep, L"pGRep无效指针",L"GDMPLab",L"2024-03-30");
    auto box = pGRep->GetBox();
    if (!box.IsPointInBox(pos) && !box.IsPointOnBox(pos))
    {
        return false;
    }

    OwnerPtr<IGraphicsBRepBody> opGBody = GetGRepBody(pDoc, pGRep);

    DBG_WARN_AND_RETURN_FALSE_UNLESS(opGBody, L"opGBody无效指针",L"GDMPLab",L"2024-03-30");

    const IBody* pGmIBody = opGBody->GetGeometry();
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pGmIBody, L"pGmIBody无效指针",L"GDMPLab",L"2024-03-30");

    PointBodyPositionTypes posType = AlgorithmPositionJudge::GetPosition(pos, pGmIBody);
    if (posType == PointBodyPositionTypes::Inside
        || posType == PointBodyPositionTypes::On)
    {
        return true;
    }

    return false;
}

bool gcmp::GbmpGraphicsNodeUtils::ClearStyleAndMaterialReferenceInGraphicsNodeAndChildren(const IDocument* pDoc, IGraphicsNode* pRoot)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pDoc, L"pDoc无效指针",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pRoot, L"pRoot无效指针",L"GDMPLab",L"2024-03-30");

    class AllGraphicsNodePathTester : public IGraphicsNodePathTester
    {
    public:
        AllGraphicsNodePathTester() = default;
        virtual ~AllGraphicsNodePathTester() {}

    public:
        virtual bool IsDesiredGraphicsNodePath(const IGraphicsNodePath& nodePath) const override { return nodePath.isValid(); }

    } allNodeTester;

    class ClearStyleAndMaterialProcessor : public IGraphicsNodeProcessor
    {
    public:
        ClearStyleAndMaterialProcessor() = default;
        virtual ~ClearStyleAndMaterialProcessor() {}

    public:
        virtual void Process(IGraphicsNode* pGraphicsNode) override
        {
            DBG_WARN_AND_RETURN_VOID_UNLESS(pGraphicsNode, L"pGraphicsNode为空。",L"GDMPLab",L"2024-03-30");
            pGraphicsNode->SetGraphicsStyleId(ElementId::InvalidID);
            pGraphicsNode->SetGraphicsMaterialId(ElementId::InvalidID);
        }
    } clearProcessor;

    OwnerPtr<IGraphicsNodePathCollector> opCollector = IGraphicsNodePathCollector::Create(pDoc, pRoot);
    opCollector->ProcessGraphicsNodes(&allNodeTester, &clearProcessor);

    return true;
}
